package com.flx.noodle.websocket.service;

import com.flx.noodle.websocket.adapter.ChatSessionAdapter;
import com.flx.noodle.websocket.adapter.RoomSessionAdapter;
import com.flx.noodle.websocket.dao.ChatDao;
import com.flx.noodle.websocket.dao.MessageDao;
import com.flx.noodle.websocket.dao.RoomDao;
import com.flx.noodle.websocket.entity.ChatMessage;
import com.flx.noodle.websocket.entity.ChatRoom;
import com.flx.noodle.websocket.entity.SSOUser;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.WsConstant;
import java.util.*;

/**
 * Created by fenglixiong on 2017/10/2.
 */
@Service
public class ChatService implements InitializingBean {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private RoomDao roomDao;
    @Autowired
    private MessageDao messageDao;

    private ChatSessionAdapter chatNotifyService;

    private RoomSessionAdapter roomNotifyService;

    public void setChatNotifyService(ChatSessionAdapter chatNotifyService) {
        this.chatNotifyService = chatNotifyService;
    }

    public void setRoomNotifyService(RoomSessionAdapter roomNotifyService) {
        this.roomNotifyService = roomNotifyService;
    }

    public int sendNewMessage(ChatMessage chatMessage){
        int ret = messageDao.insertMessage(chatMessage);
        logger.info("<<<<<<<<<<<<保存消息成功>>>>>>>>>>>>>");
        ChatRoom chatRoom = roomDao.getRoomById(chatMessage.getChatId());
        if(chatRoom!=null) {
            chatRoom.setLastMsg(chatMessage.getContent());
            roomDao.updateRoom(chatRoom);
            logger.info("更新房间信息成功！");
        }
        wsPushChatRefresh(chatMessage,"您收到一条来自["+chatMessage.getUserName()+"]新消息",new Date(),"send");
        return ret;
    }

    //连接websocket推送：某某某加入了房间
    public void connectWsPush(int chatSid, SSOUser user) {
        logger.info("enter connectWsPush");
        ChatRoom lastmsg = roomDao.getRoomById(chatSid);
        if (lastmsg == null) {
            logger.info("room[" + chatSid + "] is null");
            return;
        }

        ChatMessage msg = messageDao.getSystemMsg(chatSid, user.getUserId());
        if (msg != null) {
            Date createTime = msg.getCreateTime();
            long secDiff = (new Date().getTime() - createTime.getTime()) / 1000;
            if (secDiff < 10 * 60) {
                logger.info("user[" + user.getUserName() + "," + user.getUserId() + "] 10min内已进入过房间 sid[" + chatSid + "] 无需再提示");
                return;
            }
        }

        msg = new ChatMessage();
        msg.setChatId(chatSid);
        String content = user.getUserName() + "加入了房间";
        msg.setUserId(user.getUserId());
        msg.setContent(content);
        msg.setContentSize(content.length());
        msg.setContentType(WsConstant.CHAT_TYPE_SYSTEM);

        Date sendDate = new Date();
  /*      roadshowDao.saveRoadShowMsg(msg, sendDate);//保存消息
        roadshowService.setMsgReaded(msg, user.getUserId());//设置消息已读*/

        //wsPushChatRefresh
        wsPushChatRefresh(msg, content, sendDate, WsConstant.CHAT_TYPE_SYSTEM);
    }

    /**
     * 通知房间内的人刷新在线人数
     *
     * @param chatSid
     */
    public void onlinePush(Integer chatSid) {
        List<SSOUser> userList = chatNotifyService.getUserListInChatRoom(chatSid);

        Map<String, Object> notifyMap = new HashMap<String, Object>();

        List<Map<String, Object>> uList = new ArrayList<Map<String, Object>>();
        List<Integer> userIdList = new ArrayList<Integer>();
        for (SSOUser user : userList) {
            if (userIdList.contains(user.getUserId())) {
                continue;
            }
            userIdList.add(user.getUserId());

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userId", user.getUserId());
            map.put("userName", user.getUserName());

            uList.add(map);
        }
        notifyMap.put("list", uList);
        notifyMap.put("number", userIdList.size());

        try {
            this.logger.info("---->onlinePush socket push ChatSessionId[" + chatSid + "]\tusers:" + Arrays.toString(userIdList.toArray()));
            this.chatNotifyService.sendNotifyToWebSocketClient(chatSid,
                    notifyMap,
                    WsConstant.MSG_COMMAND_ONLINEREFLASH);
        } catch (Exception e) {
            e.printStackTrace();
            this.logger.error("sendNotifyToWebSocketClient failed", e);
        }
    }

    //撤回消息
    public void revokeMsg(ChatMessage chatMessage) {
        //数据库设置撤销
//        chatDao.updateRoadShowMsg(roadshowMsg.getId(), RoadshowMsg.KEY_CANECELSTATUS, 1);
        logger.info("revokeMsg cancel updated");

        ChatRoom lastmsg = roomDao.getRoomById(chatMessage.getChatId());
        if (lastmsg != null && lastmsg.getLastMsgTime()!=null &&
                lastmsg.getLastMsgTime().equals(chatMessage.getCreateTime())) {
            lastmsg.setLastMsg("撤回了一条消息");
            roomDao.updateRoom(lastmsg);
        }

        if (this.chatNotifyService != null) {
            wsPushChatRefresh(chatMessage, "撤回了一条消息", new Date(), WsConstant.MSG_ACTION_REVOKE);
        }
    }

    /**
     * 发送消息刷新命令给客户端，只用作：RoadshowConst.MSG_COMMAND_CHATREFLASH
     *
     * @param chatMessage
     * @param content
     * @param sendDate
     * @param action      - 聊天的协议
     */
    private List<SSOUser> wsPushChatRefresh(ChatMessage chatMessage, String content, Date sendDate, String action) {
        Map<String, Object> notifyMap = new HashMap<String, Object>();
        notifyMap.put("chatid", chatMessage.getChatId());
        notifyMap.put("content", content);
        notifyMap.put("username", chatMessage.getUserName());
        notifyMap.put("userid", chatMessage.getUserId());
        notifyMap.put("sendtime", sendDate);
        notifyMap.put("action", action);
        try {
            List<SSOUser> ret = this.chatNotifyService.sendNotifyToWebSocketClient(chatMessage.getChatId(), notifyMap,
                    WsConstant.MSG_COMMAND_CHATREFLASH);
            logger.info("ws push finished ChatSessionId[" + chatMessage.getChatId() + "]\t推送成功：" + ret.size());
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("sendMsg sendNotifyToWebSocketClient failed", e);
        }
        return null;
    }

    public int getRoomPersonNumber(String chatSessionId) {
        return this.chatNotifyService.getRoomPersonNumber(chatSessionId);
    }

    public void afterPropertiesSet() throws Exception {
        logger.info("=====================>chatService initialized....");
    }
}
